const util = require('../../utils/util');
const GeneratorTableService = require('../../service/system/generatorTableService');

async function listTables(ctx) {
	const { tableName = '', tableComment = '', page = 1, limit = 10 } = ctx.query;

	try {
		const result = await GeneratorTableService.selectDbTableByImport({
			tableName,
			tableComment,
			page: +page,
			limit: +limit,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询表列表失败: ${error.message}`);
	}
}

async function listSchemaTables(ctx) {
	const { tableName = '', tableComment = '', filterSys = 'false', page = 1, limit = 10 } = ctx.query;

	try {
		const result = await GeneratorTableService.selectDbTableNotInImport({
			tableName,
			tableComment,
			filterSys: filterSys === 'true',
			page: +page,
			limit: +limit,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询数据库表列表失败: ${error.message}`);
	}
}

async function importTables(ctx) {
	const { tableName } = ctx.request.body;

	if (!Array.isArray(tableName) || tableName.length === 0) {
		return util.fail(ctx, '表名数组不能为空');
	}

	try {
		const result = await GeneratorTableService.importTables(tableName);
		util.success(ctx, { tableName: result });
	} catch (error) {
		util.fail(ctx, `导入表失败: ${error.message}`);
	}
}

module.exports = { listTables, listSchemaTables, importTables };
